package com.shoppingmall.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by
 *  该类用来生成guava缓存
 * @author touni
 * @date 2019/3/19
 * @time 11:28
 */
public class GuavaCache {

    private  static Logger logger = LoggerFactory.getLogger(GuavaCache.class);
    private static LoadingCache<String,String> localCache =
            CacheBuilder.newBuilder().initialCapacity(1000).maximumSize(1000).expireAfterAccess(1, TimeUnit.HOURS).build(new CacheLoader<String, String>() {
                @Override
                //默认的数据加载实现  当调用get获取值的时候，若key无对应的值，就会调用这个方法进行加载
                public String load(String key) throws Exception {
                    return "null";
                }
            });


    public static void setKey(String key,String value){
        localCache.put(key,value);

    }

    public static String getKey(String key){

        try {
            String value = localCache.get(key);
            if ("null".equals(value)){
                return null;
            }

            return value;
        }catch (Exception e){
            logger.error("get cache error",e);

        }
        return null;


    }



}
